import axios from "axios";
import qs from "qs";
import type { RawAxiosRequestHeaders, ResponseType } from "axios";
const path = import.meta.env.VITE_PROXY_DOMAIN_REAL;
import { ElMessage } from "element-plus";
import NProgress from "@/utils/progress";
import router from "@/router";
import { useAppStoreWithOut } from "@/store/modules/app"

const instance = axios.create({
  // baseURL: path,
  timeout: 600000,
  headers: {
    Accept: "application/json, text/plain, */*",
    "Content-Type": "application/json",
    "X-Requested-With": "XMLHttpRequest"
  },
  paramsSerializer: params => qs.stringify(params, { indices: false })
});
//请求拦截
instance.interceptors.request.use(
  (config: any) => {
        NProgress.start();
    const store = useAppStoreWithOut()
      if(store.getToken) {
        config.headers.Authorization = store.getToken
      }
    return config;
  },
  (err: any) => {
    //拦截失败
    return Promise.reject(err);
  }
);
//响应拦截
instance.interceptors.response.use(
  (res: any) => {
    NProgress.done();
    if (res.data.code === -1){
      ElMessage.error(res.data.message)
      return Promise.reject(res.data.message);
    } 
    if (res.request.responseType === 'blob') {
      return res.data
    }
    return res.data.data

  },
  (err: any) => {
    NProgress.done();
    const msg = err.response.data.message
    if (msg) {
      ElMessage.error(msg)
    }
    if (err.response.status == 401){
      router?.push('/login')
    }
    if (err.response.statusText){
      ElMessage.error(err.response.statusText)
    }
    return Promise.reject(err);
  }
);


// 参数类型改为泛型
export default {
  get: <T>(url: string, data = {}, responseType: any = "json"): Promise<T> => {
    return instance({
      url,
      method: "get",
      params: data,
      responseType: responseType,
    }) as Promise<T>;
  },
  post: <T>(url: string, data = {}, headers?: RawAxiosRequestHeaders, responseType?: ResponseType): Promise<T> => {
    return instance({ url, method: "post", data: data, headers, responseType }) as Promise<T>;
  },
  put: <T>(url: string, data = {}): Promise<T> => {
    return instance({ url, method: "put", data: data }) as Promise<T>;
  },
  delete: <T>(url: string, data = {}): Promise<T> => {
    return instance({ url, method: "delete", data: data }) as Promise<T>;
  },
  postFile: <T>(url: string, data = {}, config:any): Promise<T> => {
    return instance({ url, method: "post", data: data, ...config }) as Promise<T>;
  }
};

